package com.dragon.aipictures.manager.upload;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import com.dragon.aipictures.Exception.BusinessException;
import com.dragon.aipictures.Exception.StateCode;
import com.dragon.aipictures.config.CosClientConfig;
import com.dragon.aipictures.domain.dto.UploadPictureResult;
import com.dragon.aipictures.manager.CosManager;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.CIObject;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.qcloud.cos.model.ciModel.persistence.ProcessResults;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Slf4j
public abstract class PictureUploadTemplate {
    @Resource
    private CosClientConfig cosClientConfig;
    @Resource
    private CosManager cosManager;

    final long ONE_M = 1024 * 1024;
//    final List<String> ALLOW_CONTENT_TYPES = Arrays.asList("jpeg", "jpg", "png", "webp","bmp","gif","image/jpeg","image/jpg","image/png","image/webp","image/bmp","image/gif");

//    上传图片
    public UploadPictureResult uploadPicture(Object inputSource,String uploadPathPrefix){
        //图片校验
        String suffix = validPicture(inputSource);
        //指定文件名，生成上传的路径
        String uuid= RandomUtil.randomString(16);
        String originalFileName = getOriginalFileName(inputSource);
        String uploadFileName=String.format("%s_%s.%s", DateUtil.formatDate(new Date()),uuid, suffix);
        String uploadPath=String.format("%s/%s",uploadPathPrefix,uploadFileName);
        File file=null;
        try{
            file=File.createTempFile(uploadPath,null);
            //处理文件来源，获得临时文件，用于上传图片的参数
            processFile(inputSource,file);
            //获得上传后的结果
            PutObjectResult putObjectResult = cosManager.putObject(uploadPath, file);
            //通过上传后的结果获得数据万象的基础处理结果
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            ProcessResults processResults = putObjectResult.getCiUploadResult().getProcessResults();
            //获得压缩图，缩略图信息，通过buildResult方法进行封装返回
            List<CIObject> objectList = processResults.getObjectList();
            if(CollUtil.isNotEmpty(objectList)){
                CIObject compressedCiObject = objectList.get(0);
                CIObject thumbnailCiObject=compressedCiObject;
                if (objectList.size()>1) {
                    thumbnailCiObject=objectList.get(1);
                }
                return buildResult(originalFileName,uploadPath, thumbnailCiObject,imageInfo);
            }
            return buildResult(originalFileName,file,uploadPath,imageInfo);

        }catch(Exception e){
            log.error("图片上传到对象存储失败",e);
            throw new BusinessException(StateCode.SYSTEM_ERROR,"图片上传失败");
        }finally {
            deleteTempFile(file);
        }
    }
    private UploadPictureResult buildResult(String originalFilename, String uploadPath, CIObject thumbnailCiObject,
                                            ImageInfo imageInfo) {
        // 计算宽高
        int picWidth = thumbnailCiObject.getWidth();
        int picHeight = thumbnailCiObject.getHeight();
        double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
        // 封装返回结果
        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        // 设置压缩后的原图地址
        uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + uploadPath);
        uploadPictureResult.setPicName(originalFilename);
        uploadPictureResult.setPicSize(thumbnailCiObject.getSize().longValue());
        uploadPictureResult.setPicWidth(picWidth);
        uploadPictureResult.setPicHeight(picHeight);
        uploadPictureResult.setPicScale(picScale);
        uploadPictureResult.setPicFormat(thumbnailCiObject.getFormat());
        uploadPictureResult.setPicColor(imageInfo.getAve());
        // 设置缩略图地址
        uploadPictureResult.setThumbnailUrl(cosClientConfig.getHost() + "/" + thumbnailCiObject.getKey());
        // 返回可访问的地址
        return uploadPictureResult;
    }

    /**
     * 封装返回结果
     *
     * @param originalFilename
     * @param file
     * @param uploadPath
     * @param imageInfo        对象存储返回的图片信息
     * @return
     */
    private UploadPictureResult buildResult(String originalFilename, File file, String uploadPath, ImageInfo imageInfo) {
        // 计算宽高
        int picWidth = imageInfo.getWidth();
        int picHeight = imageInfo.getHeight();
        double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
        // 封装返回结果
        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + uploadPath);
        uploadPictureResult.setPicName(originalFilename);
        uploadPictureResult.setPicSize(FileUtil.size(file));
//        imageInfo.
        uploadPictureResult.setPicWidth(picWidth);
        uploadPictureResult.setPicHeight(picHeight);
        uploadPictureResult.setPicScale(picScale);
        uploadPictureResult.setPicFormat(imageInfo.getFormat());
        uploadPictureResult.setPicColor(imageInfo.getAve());
        // 返回可访问的地址
        return uploadPictureResult;
    }

    //    图片校验
    public abstract String validPicture(Object inputSource);
//    获取输入源的原始文件名
    public abstract String getOriginalFileName(Object inputSource);
//    处理输入源生成本地文件
    public abstract void processFile(Object inputSource, File file) throws IOException;
//    删除临时文件
    public void deleteTempFile(File file){
        if(file==null){
            return ;
        }
        boolean delete = file.delete();
        if (!delete) {
            log.error("file delete error,filepath= {}",file.getAbsoluteFile());
        }
    }

}
